package com.sunkyc.framework.interceptor;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.sunkyc.commons.contants.GlobContants;
import com.sunkyc.commons.entity.R;
import com.sunkyc.framework.system.CacheKey.AuthroticationCacheKeys;
import com.sunkyc.framework.system.entity.LoginUser;
import com.sunkyc.framework.utils.RedisUtils;
import com.sunkyc.framework.wrapper.MyRequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 网页端验证码拦截器
 */
public class CaptchaInterceptor  implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("/auth/weblogin".equals(request.getRequestURI())){
            MyRequestWrapper reqWrapper = new MyRequestWrapper(request);
            String body = reqWrapper.getBody();
            LoginUser loginUer = JSONUtil.toBean(body, LoginUser.class);
            if(StringUtils.isBlank(loginUer.getCaptchaCode()) ||StringUtils.isBlank(loginUer.getCaptchaUuid())){
                resErro(response,"请检查验证码是否正确");
                return false;
            }
            RedisUtils redisUtils = SpringUtil.getBean(RedisUtils.class);
            String cacheCode = redisUtils.getCacheObject(AuthroticationCacheKeys.CAPTHCA_CACHE_KEY + ":" + loginUer.getCaptchaUuid());
            if(StringUtils.isBlank(cacheCode)){
                resErro(response,"验证码超时，请重新获取再进行登录");
                return false;
            }
            if(!cacheCode.equals(loginUer.getCaptchaCode())){
                resErro(response,"验证码错误,请重试");
                return false;
            }
            request.setAttribute(GlobContants.LOGIN_BODY,loginUer);
            redisUtils.deleteObject(AuthroticationCacheKeys.CAPTHCA_CACHE_KEY + ":" + loginUer.getCaptchaUuid());
            return true;
        }else {
            return true;
        }
    }
    private void resErro(HttpServletResponse response,String message) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.setStatus(HttpStatus.HTTP_BAD_REQUEST);
        PrintWriter out = response.getWriter();
        out.write(JSONUtil.toJsonStr(R.fail(HttpStatus.HTTP_BAD_REQUEST,message)));
        out.flush();
        out.close();
    }
}
